package com.tsvetanv.simpleformcontroller.example01.person.dao;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.tsvetanv.simpleformcontroller.example01.person.mvc.model.Person;

public class PersonDaoInMemoryImpl implements PersonDao {

	private Map<Integer, Person> personsMap;
	private Logger logger = Logger.getLogger(PersonDaoInMemoryImpl.class);

	// --- Constructors, Getters/Setters ---------------------------------------

	public PersonDaoInMemoryImpl() {
		// guarantee that Map reference is instantiated and ready for injection
		personsMap = new HashMap<Integer, Person>();
	}

	public Map<Integer, Person> getPersonsMap() {
		return personsMap;
	}

	public void setPersonsMap(Map<Integer, Person> personsMap) {
		this.personsMap = personsMap;
	}

	// --- Methods -------------------------------------------------------------

	public void save(Person person) {
		// it is a guarantee that always id>=0
		int id = personsMap.size();
		personsMap.put(new Integer(id), person);

		// --- This logging is for "Redirect After Submit" Pattern
		// (known also as "redirect after POST")
		// page 183, chap.6, book "Expert SpringMVC"
		// To see the result right click with the mouse on the successPage and
		// click "Reload"
		// logger.info("------- START ---------");
		// for (Map.Entry<Integer, Person> entry : personsMap.entrySet()) {
		// logger.info(entry.getValue().getName());
		// }
		// logger.info("------- END ---------");
		// --- End logging
	}

	public void delete(Person person) {
		int targetId = -1;
		for (Map.Entry<Integer, Person> entry : personsMap.entrySet()) {
			if (entry.getValue().equals(person)) {
				targetId = entry.getKey();
				break;
			}
		}
		if (targetId > -1) {
			personsMap.remove(targetId);
		}
		// else do nothing because the target is not in the map
	}

	public boolean contains(Person person) {
		int targetId = -1;
		for (Map.Entry<Integer, Person> entry : personsMap.entrySet()) {
			if (entry.getValue().equals(person)) {
				targetId = entry.getKey();
				break;
			}
		}
		if (targetId > -1) {
			return true;
		}
		// else the target is not in the map
		return false;
	}
}
